package com.ruoyi.maode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.FrequencyEums;
import com.ruoyi.common.enums.LevelEums;
import com.ruoyi.common.exception.UtilException;
import com.ruoyi.common.utils.file.ImageUtils;
import com.ruoyi.common.utils.poi.ReadExcelUtil;
import com.ruoyi.maode.domain.dto.AddPartDTO;
import com.ruoyi.maode.domain.dto.QueryPartDTO;
import com.ruoyi.maode.domain.entity.Part;
import com.ruoyi.maode.domain.entity.PartImage;
import com.ruoyi.maode.domain.entity.PartSize;
import com.ruoyi.maode.domain.vo.ImageDetailVO;
import com.ruoyi.maode.domain.vo.PartDetailVO;
import com.ruoyi.maode.domain.vo.PartSizeVO;
import com.ruoyi.maode.mapper.PartMapper;
import com.ruoyi.maode.service.PartImageService;
import com.ruoyi.maode.service.PartService;
import com.ruoyi.maode.service.PartSizeService;
import com.ruoyi.web.core.config.ResultDTO;
import com.ruoyi.web.util.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 零件接口实现类
 * @author zhangwenqiang
 */
@Service
public class PartServiceImpl extends ServiceImpl<PartMapper, Part> implements PartService {

    private static final Logger log = LoggerFactory.getLogger(PartServiceImpl.class);

    @Value("${ruoyi.profile}")
    private String filePath;

    @Value("${server.url}")
    private String serverUrl;

    @Autowired
    private PartImageService partImageService;

    @Autowired
    private PartSizeService partSizeService;

    @Autowired
    private PartMapper partMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addPart(AddPartDTO dto) {

        Part part = new Part();
        BeanUtils.copyProperties(dto,part);
        if (dto.getFilePath() != null) {
            part.setFile(dto.getFilePath());
        }
        if (dto.getImages() != null) {
            String urlString = dto.getImages().stream()
                    .map(ImageDetailVO::getUrl)
                    .collect(Collectors.joining(","));
            part.setImg(urlString);
        }

        // 查询是否存在零件
        Part partResp = partMapper.selectOne(new LambdaQueryWrapper<Part>()
                .eq(Part::getPartCode, dto.getPartCode())
                .eq(Part::getIsDelete,Constants.CONSTANTS_ZERO));
        if (partResp != null) {
            throw new UtilException("零件已存在，请勿重复新增!");
        }
        int in = baseMapper.insert(part);

        Part resp = partMapper.selectOne(new LambdaQueryWrapper<Part>()
                .eq(Part::getPartCode, dto.getPartCode())
                .eq(Part::getIsDelete,Constants.CONSTANTS_ZERO));

        // 获取Excel表中的检基数据
        try {
            String replacePath = dto.getFilePath().replace(Constants.RESOURCE_PREFIX, "");
            List<List<Object>> lists = ReadExcelUtil.readExcel(filePath +replacePath);
            // 获取图片的数据
            List<Object> imageList = lists.get(lists.size() - 1);
            // 将List<Object>转换为List<String>
            List<String> stringList = castListString(imageList);
            String image = stringList.stream().collect(Collectors.joining(","));
            PartImage partImage = new PartImage();
            partImage.setImage(image);
            partImage.setPartId(String.valueOf(resp.getId()));
            // 保存零件对应的图片
            partImageService.save(partImage);

            // 检基与零件建立绑定关系新增关系表
            for (int i = 0; i < lists.size() - 1; i++) {
                PartSize partSize = new PartSize();
                List<Object> objectList = lists.get(i);
                List<String> entry = castListString(objectList);
                String serialNum = "";
                if (entry.get(0).contains(".0")) {
                    serialNum = entry.get(0).substring(0, entry.get(0).indexOf("."));
                }
                partSize.setSerialNumber(serialNum);
                partSize.setDetection(entry.get(1));
                partSize.setMin(entry.get(2));
                partSize.setMax(entry.get(3));
                partSize.setLevel(LevelEums.getCodeByDescription(entry.get(4)));
                partSize.setTestMethod(entry.get(5));
                partSize.setFrequency(FrequencyEums.getCodeByDescription(entry.get(6)));
                partSize.setPartId(String.valueOf(resp.getId()));
                partSizeService.save(partSize);
            }
        } catch (IOException e) {
            // 处理IOException
            throw new UtilException(e.getMessage());
        }


        return in;
    }

    @Override
    public int deleteById(Long id) {
        int update = partMapper.update(new Part(), new LambdaUpdateWrapper<Part>()
                .eq(Part::getId, id)
                .set(Part::getIsDelete, Constants.CONSTANTS_ONE));
        if (update < 1){
            throw new UtilException("删除失败，请确认！");
        }
        // TODO
        // 删除零件对应检测数据、检测气泡图数据
        partSizeService.remove(new LambdaQueryWrapper<PartSize>().eq(PartSize::getPartId, id));
        partImageService.remove(new LambdaQueryWrapper<PartImage>().eq(PartImage::getPartId, id));
        return update;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByIds(List<Long> ids) {
        int update = partMapper.update(new Part(), new LambdaUpdateWrapper<Part>()
                .in(Part::getId, ids)
                .set(Part::getIsDelete, Constants.CONSTANTS_ONE));
        if (update < 1) {
            throw new UtilException("删除失败，请确认！");
        }
        // TODO
        // 删除零件对应删除检测数据
        return update;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int editPart(AddPartDTO dto) {
        String imageUrl;
        Part part = new Part();
        if (dto.getImages() != null) {
            imageUrl = dto.getImages().stream()
                    .map(ImageDetailVO::getUrl)
                    .collect(Collectors.joining(","));
            part.setImg(imageUrl);
        } else {
            part.setPartCode(dto.getPartCode());
            part.setPartName(dto.getPartName());
            part.setPartWeight( dto.getPartWeight());
            part.setPartDescription(dto.getPartDescription());
            part.setPartDescription(dto.getPartDescription());
            part.setModel(dto.getModel());
            part.setType( dto.getType());
            part.setImg(null);
        }
        // 判定是否更新了检基
        if (Constants.CONSTANTS_ONE.equals(dto.getIsEditFile())) {
            // 获取Excel表中的检基数据
            try {
                String replacePath = dto.getFilePath().replace(Constants.RESOURCE_PREFIX, "");
                List<List<Object>> lists = ReadExcelUtil.readExcel(filePath +replacePath);

                // 获取图片的数据
                List<Object> imageList = lists.get(lists.size() - 1);
                // 将List<Object>转换为List<String>
                List<String> stringList = castListString(imageList);
                String image = stringList.stream().collect(Collectors.joining(","));
                // 更新零件对应的图片
                partImageService.update(new PartImage(), new LambdaUpdateWrapper<PartImage>()
                        .eq(PartImage::getPartId, dto.getId())
                        .set(PartImage::getImage, image)
                );
                // 编辑零件尺寸数据表
                // 先删除之前的数据
                partSizeService.remove(new LambdaQueryWrapper<PartSize>().eq(PartSize::getPartId, dto.getId()));

                for (int i = 0; i < lists.size() - 1; i++) {
                    PartSize partSize = new PartSize();
                    List<Object> objectList = lists.get(i);
                    List<String> entry = castListString(objectList);
                    String serialNum = "";
                    if (entry.get(0).contains(".0")) {
                        serialNum = entry.get(0).substring(0, entry.get(0).indexOf("."));
                    }
                    partSize.setSerialNumber(serialNum);
                    partSize.setDetection(entry.get(1));
                    partSize.setMin(entry.get(2));
                    partSize.setMax(entry.get(3));
                    partSize.setLevel(LevelEums.getCodeByDescription(entry.get(4)));
                    partSize.setTestMethod(entry.get(5));
                    partSize.setFrequency(FrequencyEums.getCodeByDescription(entry.get(6)));
                    partSize.setPartId(String.valueOf(dto.getId()));
                    partSizeService.save(partSize);
                    part.setFile(dto.getFilePath());
                }

            } catch (IOException e) {
                // 处理IOException
                throw new UtilException(e.getMessage());
            }
        }
        // 编辑零件数据
        int update = partMapper.update(part, new LambdaUpdateWrapper<Part>()
                .eq(Part::getId, dto.getId()));
        return update;
    }

    @Override
    public Page<Part> selectPartList(PageQuery<QueryPartDTO> param) {
        Page page = new Page<QueryPartDTO>(param.getPage(), param.getPageSize());
        QueryPartDTO dto = param.getData();
        return partMapper.selectPartList(page,dto);
    }

    @Override
    public PartDetailVO getDetail(Long id) {
        Part part = partMapper.getDetail(id);
        PartDetailVO vo = new PartDetailVO();
        BeanUtils.copyProperties(part,vo);
        if(part.getImg() != null){
            List<String> list = castList(part.getImg());
            List<ImageDetailVO> imageDetailVOS = new ArrayList<>();

            // 图片地址加上服务器地址url
            for (String url : list) {
                ImageDetailVO imageDetailVO = new ImageDetailVO();
                imageDetailVO.setUrl(url);
                imageDetailVO.setName(ImageUtils.getImageName(url));
                imageDetailVOS.add(imageDetailVO);
            }
            vo.setImages(imageDetailVOS);
        }

        // excel文件加上服务器地址url
        vo.setFilePath(serverUrl + part.getFile());
        vo.setFileName(ImageUtils.getImageName(serverUrl + part.getFile()));
        return vo;
    }

    /**
     * List<Object>转换为List<String>
     * @param list
     * @return
     */
    private List<String> castListString(List<Object> list) {
        // 使用 Stream 将 List<Object> 转换为 List<String>
        List<String> stringList = list.stream()
                .map(String::valueOf)
                .collect(Collectors.toList());
        return stringList;
    }


    /**
     * String"a,b,c"转换为List<String>["a","b","c"]
     * @param string
     * @return
     */
    private List<String> castList(String string) {
        List<String> list = Arrays.stream(string.split(","))
                .collect(Collectors.toList());
        return list;
    }


}
